<template lang="html">
 <div class="main">
   <panel title="吸毒人员复吸预测" class="panel">
     <!-- 预测图表 -->
     <div class="chart" id="forecast"  v-loading="loadingMap" element-loading-text="拼命加载中" element-loading-background="transparent">
     </div>
   </panel>
   <panel title="个体复吸预测" class="panel right">
       <div class="body">
         <div class="item select">
           <!-- <el-input placeholder="请输入需要预测的人名" v-model="personal.value" @keyup.enter.native="search" class="input-with-select" size="small">
            <el-button slot="append" icon="el-icon-search"  @click="search"></el-button>
            </el-input> -->
            <el-select
               v-model="personal.value"
               filterable
               remote
               reserve-keyword
               size="small"
               placeholder="请输入需要预测的人名"
               :remote-method="search"
               :loading="loading">
               <el-option
                 v-for="item in personal.data"
                 :key="item.XYRBH"
                 :label="`${item.XM}`"
                 :value="item.XYRBH">
                 <span style="float: left; width: 50px; text-align: left;">{{ item.XM }}</span>
                 <span style="font-size: 12px;float: left; width: 135px; text-align: left;">
                   {{ item.IDCARD }}</span>
                 <span style="font-size: 12px; font-size: 13px">{{ item.ISFXMC }}</span>
               </el-option>
             </el-select>
         </div>
         <div class="item item-center">
           <!-- 雷达图 -->
           <div class="chart" id="forecast_radar">
           </div>
         </div>
         <div class="item text" v-show="showResult && personal.value">
           <div class="item-name" style="font-size: 15px;">
             <img src="../../assets/人名.png">{{personal.name}}
            </div>
           <div class="item-name" style="font-size: 15px;">
             <img src="../../assets/身份证.png">{{personal.idcard}}
           </div>
           <div class="item-name" style="font-size: 15px;">
             <span>监管责任人：</span>{{personal.supervisor}}
           </div>
           <div :class="['item-name', resultCss]">
             <!-- 评估分数 -->
             <span>评估分数：</span>{{personal.score}}分
           </div>
           <div :class="['item-name', resultCss]">
             <!-- 分析结果 -->
             <span>分析结果：</span>{{result}}
           </div>
         </div>
       </div>
   </panel>
 </div>
</template>

<script>
import panel from '@/components/panel.vue';
import fetchDistrictInfo from '../warning/fetchDistrictInfo';
import fetchPersons from './fetchPersons';
import fetchDrugAgain from './fetchDrugAgain';
// import {fetchPersons, fetchDrugAgain, fetchDistrictInfo} from '@/common/api';
export default {
  data () {
    return {
      showResult: false,
      loading: false,
      loadingMap: false,
      charts: {},
      districts: [],
      personal: { // 个人分析情况
        value: '',
        name: '',
        idcard: '',
        supervisor: '',
        score: 0,
        data: []
      }
    };
  },
  components: {
    panel
  },
  watch: {
    'personal.value' (value) {
      let p = this.personal.data.find(d => d.XYRBH === value);
      this.personal.score = p.score;
      this.personal.name = p.XM;
      this.personal.idcard = p.IDCARD;
      this.personal.supervisor = this.districts.find(s => s.name === p.XJZDMC).personSupervisor;
      this.drawRadar('forecast_radar', p.data);
      this.showResult = true;
    }
  },
  computed: {
    result () {
      return this.personal.score <= 61 ? `复吸风险低` : (this.personal.score <= 75 ? `复吸风险中` : `复吸风险高`);
    },
    resultCss () {
      return this.personal.score <= 61 ? `result-low` : (this.personal.score <= 75 ? `result-center` : `result-high`);
    }

  },
  methods: {
    rnd (n, m) {
      return Math.floor(Math.random() * (m - n + 1) + n);
    },
    search (value) {
      if (!value) {
        return;
      }
      this.loading = true;
      // fetchPersons({name: value}).then(res => {
      let res = fetchPersons;
      this.loading = false;
      this.personal.data = res.data;
      this.personal.data.forEach(p => {
        let num = 60;
        let min = 0;
        if (p.ISFXMC === '复吸人员') {
          min = 50;
          num = 100;
        }
        let data = [this.rnd(min, num), this.rnd(min, num), this.rnd(min, num), this.rnd(min, num), this.rnd(min, num), this.rnd(min, num), this.rnd(min, num), this.rnd(min, num)];
        let score = 0;
        data.forEach(d => {
          score += d;
        });
        p.data = data;
        p.score = parseInt(score / data.length);
      });
      // }).catch(err => {
      //   console.log(err);
      //   this.$message(`查询失败！请联系负责人`);
      // });
    },
    drawRadar (id, data = [0, 0, 0, 0, 0, 0, 0, 0]) {
      let colors = ['#FF6633', '#FDD033', '#00CC33'];
      let c = [colors[this.personal.score <= 61 ? 2 : (this.personal.score <= 75 ? 1 : 0)]];
      let hasValue = false;
      if (data.find(d => d > 0)) {
        hasValue = true;
      }
      let chart = this.charts[id];
      let option = {
        tooltip: {
          trigger: 'item'
        },
        color: c,
        polar: [
          {
            nameGap: 8, // 图中工艺等字距离图的距离
            radius: 90,
            center: ['50%', '50%'], // 图的位置
            name: {
              show: true,
              color: '#777777'
            },
            indicator: [
              {text: '滥药历史', max: 100},
              {text: '社交状况', max: 100},
              {text: '工作状况', max: 100},
              {text: '家庭状况', max: 100},
              {text: '健康状况', max: 100},
              {text: '精神状况', max: 100},
              {text: '行为模式', max: 100},
              {text: '经济状况', max: 100}
            ]
          }
        ],
        calculable: true,
        series: [
          {
            name: '雷达图',
            type: 'radar',
            data: [
              {
                value: hasValue ? data : [],
                name: '复吸预测模型'
              }
            ]
          }
        ]
      };
      chart.setOption(option, true);
    },
    draw (id, data, fxdata) {
      let chart = this.charts[id];
      let month = new Date().getMonth();
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter (d) {
            console.log(d);
            let result = [];
            result.push(d[0].axisValue, '<br/>');
            result.push('<div style="text-align: left">');
            d.forEach(i => {
              if (i.data > 0) {
                result.push(i.marker, i.seriesName, i.data, '<br/>');
              }
            });
            result.push('</div>');
            return result.join('');
          }
        },
        calculable: true,
        legend: {
          data: ['吸毒人数', '复吸人数', '复吸率', '预测吸毒人数', '预测复吸人数']
        },
        color: ['#4196BB', '#7FB3E0', '#C8AA3E'],
        xAxis: [
          {
            type: 'category',
            data: data.map((d, index) => (index + 1) + '月')
          },
          {
            type: 'category',
            data: data.map((d, index) => (index + 1) + '月')
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '人数',
            axisLabel: {
              formatter: '{value} 人'
            }
          },
          {
            type: 'value',
            name: '复吸率',
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: [
          {
            name: '吸毒人数',
            type: 'bar',
            data: data.map((d, i) => {
              if (i <= month) {
                return d;
              }
              return 0;
            })
          },
          {
            name: '复吸人数',
            type: 'bar',
            data: fxdata.map((d, i) => {
              if (i <= month) {
                return d;
              }
              return 0;
            })
          },
          {
            name: '复吸率',
            type: 'line',
            yAxisIndex: 1,
            data: data.map((d, i) => {
              return (fxdata[i] / d * 100).toFixed(2);
            })
          },
          {
            name: '预测吸毒人数',
            type: 'bar',
            xAxisIndex: 1,
            data: data.map((d, i) => {
              if (i <= month) {
                return 0;
              }
              return d;
            }),
            itemStyle: {
              normal: {
                color: 'rgba(65,150,187,.3)'
              }
            }
          }, {
            name: '预测复吸人数',
            type: 'bar',
            xAxisIndex: 1,
            data: fxdata.map((d, i) => {
              if (i <= month) {
                return 0;
              }
              return d;
            }),
            itemStyle: {
              normal: {
                color: 'rgba(127,179,224,.3)'
              }
            }
          }
        ]
      };
      // let option = {
      //   tooltip: {
      //     trigger: 'axis',
      //     axisPointer: { // 坐标轴指示器，坐标轴触发有效
      //       type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      //     },
      //     formatter (d) {
      //       console.log(d);
      //       let result = [];
      //       result.push(d[0].axisValue, '<br/>');
      //       result.push('<div style="text-align: left">');
      //       d.forEach(i => {
      //         if (i.data > 0) {
      //           result.push(i.marker, i.seriesName, i.data, '<br/>');
      //         }
      //       });
      //       result.push('</div>');
      //       return result.join('');
      //     }
      //   },
      //   calculable: true,
      //   legend: {
      //     data: ['吸毒人数', '复吸人数', '复吸率', '预测复吸人数']
      //   },
      //   color: ['#4196BB', '#7FB3E0'],
      //   xAxis: [
      //     {
      //       type: 'category',
      //       // data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      //       data: data.map((d, index) => (index + 1) + '月')
      //     },
      //     {
      //       type: 'category',
      //       // data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      //       data: data.map((d, index) => (index + 1) + '月')
      //     }
      //   ],
      //   yAxis: [
      //     {
      //       type: 'value',
      //       name: '人数',
      //       axisLabel: {
      //         formatter: '{value} 人'
      //       }
      //     },
      //     {
      //       type: 'value',
      //       name: '复吸率',
      //       axisLabel: {
      //         formatter: '{value} %'
      //       }
      //     }
      //   ],
      //   series: [
      //     {
      //       name: '吸毒人数',
      //       type: 'bar',
      //       data: data.map((d, i) => {
      //         if (i <= month) {
      //           return d;
      //         }
      //         return 0;
      //       })
      //     },
      //     {
      //       name: '复吸人数',
      //       type: 'bar',
      //       data: fxdata.map((d, i) => {
      //         if (i <= month) {
      //           return d;
      //         }
      //         return 0;
      //       })
      //     },
      //     {
      //       name: '复吸率',
      //       type: 'line',
      //       yAxisIndex: 1,
      //       data: data.map((d, i) => {
      //         return (fxdata[i] / d * 100).toFixed(2);
      //       }),
      //       itemStyle: {
      //         normal: {
      //           color: function (params) {
      //             return '#C8AA3E';
      //           },
      //           lineStyle: {
      //             color: '#C8AA3E'
      //           }
      //         }
      //       }
      //     },
      //     {
      //       name: '预测复吸人数',
      //       type: 'bar',
      //       xAxisIndex: 1,
      //       barWidth: 20, // 固定柱子宽度
      //       data: fxdata.map((d, i) => {
      //         if (i <= month) {
      //           return 0;
      //         }
      //         return d;
      //       }),
      //       itemStyle: {
      //         normal: {
      //           color: '#c2cccc'
      //         }
      //       }
      //     }
      //   ]
      // };
      chart.setOption(option);
    },
    fetchData () {
      this.loadingMap = true;
      // fetchDrugAgain().then(res => {
      let res = fetchDrugAgain;
      res.data.sort((a, b) => parseInt(a.YUE) < parseInt(b.YUE) ? -1 : 1);
      this.loadingMap = false;
      this.draw('forecast', res.data.map(d => parseInt(d.XDRS * 10000)), res.data.map(d => parseInt(d.FXRS * 10000)));
      // }).catch(err => {
      //   console.log(err);
      //   this.$message(`加载数据失败！请联系负责人`);
      // });
    }
  },
  mounted () {
    this.$nextTick(_ => {
      this.charts['forecast_radar'] = this.$echarts.init(document.getElementById('forecast_radar'));
      this.charts['forecast'] = this.$echarts.init(document.getElementById('forecast'));
      window.addEventListener('resize', () => {
        this.charts['forecast_radar'].resize();
        this.charts['forecast'].resize();
      });
    });
    setTimeout(_ => {
      this.loadingMap = true;
      this.fetchData();
      this.drawRadar('forecast_radar');
      // fetchDistrictInfo().then(res => {
      let res = fetchDistrictInfo;
      this.districts = res.data;
      // }).catch(err => {
      //   console.log(err);
      // });
    }, 100);
  }
};
</script>

<style lang="css" scoped>
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  .panel {
    margin-left: 20px;
    position: relative;
    .chart {
      margin-top: 10px;
      position: relative;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
      width: 100%;
      height: 100%;
    }
    .body {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      vertical-align: middle;
      align-items: center;
      .item {
        height: 40px;
        line-height: 40px;
      }
      .select {
        width: 90%;
        margin-bottom: 5px;
        .el-select {
          width: 100%;
        }
      }
      .item-center {
          height: 60%;
          width: 100%;
          .chart {
            width: 100%;
            height: 85%;
          }
      }
      .text {
        font-size: 18px;
        color: #666;
        text-align: left;
        margin-top: -20px;
        div {
          line-height: 30px;
        }
        .item-name {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          img {
            width: 25px;
            height: 25px;
          }
        }
      }
    }
  }
  .panel:first-child {
    margin-left: 0px;
  }
  .right {
    width: 40%;
  }
}

</style>
<style>
.result-high {
  font-size: 18px;
  color: rgb(222,102,31);
}
.result-center {
  font-size: 18px;
  color: rgb(200,170,62);
}
.result-low {
  font-size: 18px;
  color: rgb(0,204,51);
}
</style>
